import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Create by chenhd on 2021/8/28.
 * 方法十二：使用CompletableFuture allOf用法，当然此处换成anyOf也能达到一样的效果
 */
public class ConcurrentTask13 {
    public String str;

    public static void main(String[] args) {
        ConcurrentTask13 concurrentTask = new ConcurrentTask13();
        //注意：生产环境中慎用这种直接用工具类创建的方法，因为他可能使用了无界队列、拒绝策略、线程工厂类不是你想要的，除非你明确知道就是你想要的
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        CompletableFuture completableFuture =
                CompletableFuture.runAsync(concurrentTask::putStr, executorService);

        CompletableFuture all = CompletableFuture.allOf(completableFuture);
        all.join();
        System.out.println(concurrentTask.getStr());

        //不关闭线程池，主线程不会退出
        executorService.shutdown();
    }

    public void putStr() {
        try {
            TimeUnit.SECONDS.sleep(5);
            this.str = "hello concurrent.";
        } catch (InterruptedException e) {
            //log error
            e.printStackTrace();
        }
    }

    public String getStr() {
        return str;
    }
}
